<template>
  <div class="container">
    <!-- 商品分类面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/' }">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>新增商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 新增商品信息提示 -->
      <el-alert
        title="新增商品温馨提示"
        type="info"
        :closable="false"
        description=""
        show-icon>
        <template>
          <p>请先进行商品分类的选择</p>
          <p>只允许选择新增商品所属的三级分类</p>
          <p>当该商品所属三级商品分类被选中后方可进行后续新增信息的操作</p>
        </template>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="activeCurrentTab" align-center finish-status="success">
        <el-step title="基本信息" icon="el-icon-s-order" value="1"></el-step>
        <el-step title="商品参数" icon="el-icon-s-fold" value="2"></el-step>
        <el-step title="商品属性" icon="el-icon-s-operation" value="3"></el-step>
        <el-step title="商品图片" icon="el-icon-picture" value="4"></el-step>
        <el-step title="商品描述" icon="el-icon-s-comment" value="5"></el-step>
        <el-step title="完成提交" icon="el-icon-upload" value="6"></el-step>
      </el-steps>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 选项切换面板 -->
      <el-form>
        <el-tabs tab-position="left" v-model="selectCurrentTab" style="height: 200px;" @tab-click="handleTabsChange" :before-leave="handlePreventActiveChange">
          <el-tab-pane label="基本信息" name="0">
            <!-- 级联选择器 -->
            <div class="block">
              <!-- 级联选择器标题 -->
              <el-tag
                type="success"
                effect="plain">
                请先选择新增商品所属三级分类
              </el-tag>
              <el-cascader
                ref="cascaderRef"
                v-model="cascaderSelectTrueArr"
                :options="categoryOptionsData"
                :props="cascaderConfig"
                clearable
                placeholder="请为新增商品选择所属的三级分类..."
                @change="handleSelectCategoryChange"></el-cascader>
              </div>
            <el-form :model="addGoodBaseInfoForm" :disabled="addGoodBaseInfoFormBool" ref="addGoodBaseInfoFormRef" :rules="addGoodBaseInfoFormRules" label-position="top" label-width="100">
              <el-form-item label="新增商品名称" prop="goods_name" label-width="110px">
                <el-input v-model="addGoodBaseInfoForm.goods_name" placeholder="请输入新的的商品名称..." autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="新增商品价格" prop="goods_price"  label-width="110px">
                <el-input v-model.number="addGoodBaseInfoForm.goods_price" type="number" placeholder="请输入新的商品价格..." autocomplete="off">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="新增商品库存" prop="goods_number" label-width="110px">
                <el-input v-model.number="addGoodBaseInfoForm.goods_number" type="number" placeholder="请输入新商品的库存..." autocomplete="off">
                  <template slot="append">件</template>
                </el-input>
              </el-form-item>
              <el-form-item label="新增商品重量" prop="goods_weight" label-width="110px">
                <el-input v-model.number="addGoodBaseInfoForm.goods_weight" type="number" placeholder="请输入新商品单件重量..." autocomplete="off">
                  <template slot="append">克</template>
                </el-input>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 商品动态参数 -->
            <div class="item-manyAttr" v-for="itemAttrObj in localCategoryAttrManyData" :key="itemAttrObj.attr_id">
              <el-checkbox-group v-model="itemAttrObj.attrNew_vals">
                <el-checkbox v-for="(itemArrtValArr, i) in itemAttrObj.attr_vals" :key="i" :label="itemArrtValArr" border></el-checkbox>
                <el-divider content-position="right">{{itemAttrObj.attr_name}} <i class="el-icon-s-tools"></i></el-divider>
              </el-checkbox-group>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 商品固定属性 -->
            <div class="item-manyAttr" v-for="itemAttrObj in localCategoryAttrOnlyData" :key="itemAttrObj.attr_id">
              <el-checkbox-group v-model="itemAttrObj.attrNew_vals">
                <el-checkbox v-for="(itemArrtValArr, i) in itemAttrObj.attr_vals" :key="i" :label="itemArrtValArr" border></el-checkbox>
                <el-divider content-position="right"> {{itemAttrObj.attr_name}} <i class="el-icon-s-tools"></i></el-divider>
              </el-checkbox-group>
            </div>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
          <!-- 上传图片信息提示 -->
          <el-alert
            title="商品图片上传温馨提示"
            type="info"
            :closable="false"
            description=""
            show-icon>
            <template>
              <p>支持bmp,jpg,png,ai,raw,WMF,webp等常用图片格式</p>
              <p>画面质量应清晰不模糊，并应显示在画布上，照片应有足够的亮度。</p>
              <p>商品的主画面超过800*800像素，提供5张图片,产品描述需4到6张插图</p>
              <p>主画面中不应有大的黑色投影或反射,产品图片中不得有与产品本身无关的内容</p>
            </template>
          </el-alert>
          <!-- 图片上传模块 -->
          <div class="upload-pic">
            <el-upload
              :action="picUploadAddressURL"
              :headers="setHeader"
              :file-list="goodPicUploadFileList"
              list-type="picture-card"
              :on-success="handleUpSuccess"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="scop">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="scop.file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                    >
                      <i class="el-icon-zoom-in"
                      @click="handlePictureCardPreview(scop)"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                    >
                      <i class="el-icon-delete"
                      @click="handleRemovePic(scop)"></i>
                    </span>
                  </span>
                </div>
            </el-upload>
          </div>
          </el-tab-pane>
          <el-tab-pane label="商品描述" name="4">
          <!-- 关于商品描述的提示 -->
          <el-alert
            title="商品详情描述温馨提示"
            type="info"
            :closable="false"
            description=""
            show-icon>
            <template>
              <p>产品描述中不得有与产品本身无关的内容</p>
              <p>不要在商品描述中出现独家、惟一等这些词汇，电商平台不止一家在卖同样的商品</p>
              <p>不要在商品描述中出现“最”这个词，比如说最好、最新款、最流行、最便宜、最符合等</p>
              <p>商品描述中也禁用“绝对”一词，比如绝对实用、绝对适合、绝对新潮、绝对实惠、绝对推荐等</p>
            </template>
          </el-alert>
          <!-- 富文本编辑器区域 -->
            <quill-editor v-model="addGoodBaseInfoForm.goods_introduce"
                ref="myQuillEditor"
                theme="snow"
                :options="quillEditOption">
            </quill-editor>
            <!-- 商品上传预览 -->
              <el-tag
                class="goodAllReady"
                type="danger"
                @click="handleTotlePanePage"
                effect="dark">
                <i slot="" class="el-icon-magic-stick"></i>
                商品信息已确认填写完成，点击进入预览
              </el-tag>
          </el-tab-pane>
          <el-tab-pane class="showReadyGood" label="完成提交" disabled name="5">
            <el-form label-position="left" label-width="200px">
              <el-form-item label="新增商品所属分类">
                <el-tag effect="dark" >{{currentCategoryName}}</el-tag>
              </el-form-item>
              <el-form-item label="新增商品名称">
                <el-tag effect="dark" v-if="addGoodBaseInfoForm.goods_name">
                  {{addGoodBaseInfoForm.goods_name}}
                </el-tag>
                <el-tag type="danger" effect="dark" v-else>
                  商品名称必须填写，请您返回商品基本信息填写
                </el-tag>
              </el-form-item>
              <el-form-item label="新增商品价格">
                <el-tag effect="dark" v-if="addGoodBaseInfoForm.goods_price">
                  {{`￥ ${addGoodBaseInfoForm.goods_price.toFixed(2)} 元`}}
                </el-tag>
                <el-tag type="danger" effect="dark" v-else>
                  商品价格必须填写，请您返回商品基本信息填写
                </el-tag>
              </el-form-item>
              <el-form-item label="新增商品库存">
                <el-tag effect="dark" v-if="addGoodBaseInfoForm.goods_number">
                  {{`${addGoodBaseInfoForm.goods_number} 件`}}
                </el-tag>
                <el-tag type="danger" effect="dark" v-else>
                  商品库存必须填写，请您返回商品基本信息填写
                </el-tag>
              </el-form-item>
              <el-form-item label="新增商品重量">
                <el-tag effect="dark" v-if="addGoodBaseInfoForm.goods_weight">
                  {{`${addGoodBaseInfoForm.goods_weight} 克`}}
                </el-tag>
                <el-tag type="danger" effect="dark" v-else>
                  商品单件重量必须填写，请您返回商品基本信息填写
                </el-tag>
              </el-form-item>
              <el-form-item label="新增商品描述信息">
                <p v-if="addGoodBaseInfoForm.goods_introduce">
                  {{addGoodBaseInfoForm.goods_introduce}}
                </p>
                <el-tag  type="warning" effect="dark" v-else>
                  商品描述信息为可选项，建议您填写...
                </el-tag>
              </el-form-item>
              <el-form-item label="新增商品图片信息">
                <el-image
                  style="width: 100px; height: 100px"
                  v-for="item in goodPicUploadFileList"
                  :key="item.uuid"
                  :src="item.url"
                  :preview-src-list="srcList">
                </el-image>
              </el-form-item>
            </el-form>
            <!-- 商品上传预览 -->
            <el-tag
              class="goodAllReady submitBtn"
              type="success"
              @click="handleAddGoodSubmit"
              effect="dark">
              <i slot="" class="el-icon-warning"></i>
              商品信息已确认无误，确认提交至数据库
            </el-tag>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="dialogShowPictureBool">
      <el-image
      :src="showPictureURL"
      fit="contain"
      >
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
    </el-dialog>
  </div>
</template>

<script>
// 导入loadsh
import _ from 'lodash'
export default {
  name: 'AddGoods',
  created () {
    // 发请求获取商品分类数据源
    this.getCatgoryListData()
  },
  data () {
    return {
      // 当前激活步骤条选项类型数字
      activeCurrentTab: 0,
      // 当前选项卡激活项类型字符串
      selectCurrentTab: '0',
      // 当前商品三级分类ID
      currentCategoryID: 0,
      // 当前商品所属分类Name
      currentCategoryName: '',
      // 新增表单禁用状态
      addGoodBaseInfoFormBool: true,
      // 图片预览对话框
      dialogShowPictureBool: false,
      // 展示图片URL
      showPictureURL: '',
      // 级联选择器选中项数组-goods_cat
      cascaderSelectTrueArr: [],
      // 页面初始化级联选择器商品分类数据源
      categoryOptionsData: [],
      // 级联选择器配置选项
      cascaderConfig: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
      },
      // 富文本编辑器配置项
      quillEditOption: {
        theme: 'snow',
        placeholder: '请输入对新增商品的描述信息...'
      },
      // 图片上传action地址
      picUploadAddressURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 当前商品基本信息双绑的数据-------------
      addGoodBaseInfoForm: {
        goods_name: '',
        // 以，分割的分类列表
        goods_cat: '',
        goods_price: '',
        goods_number: '',
        goods_weight: '',
        // 商品介绍
        goods_introduce: '',
        // 图片临时路径
        pics: [],
        // 商品参数，包含动态/静态参数
        attrs: []
      },
      // 将服务器 动态参数 通过loadsh 深拷贝至本地
      // attrNew_vals 为用户选择动态参数数组
      localCategoryAttrManyData: [],
      // 将服务器 动态参数 通过loadsh 深拷贝至本地
      // attrNew_vals 为用户选择固定参数数组
      localCategoryAttrOnlyData: [],
      // 图片预览
      srcList: [],
      // 图片上传数据列表
      goodPicUploadFileList: [],
      // 新增商品校验规则----------------------------
      addGoodBaseInfoFormRules: {
        goods_name: [
          { required: true, message: '商品名称必须填写....', trigger: 'blur' },
          { min: 1, message: '商品名称不得少于10个字符...', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '商品价格必须填写....', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '商品库存必须填写....', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '商品单件重量必须填写....', trigger: 'blur' }
        ]
      }
      // -----当前商品三级分类 服务器获取动态参数 数据源-----
      // categoryAttrManyData: [],
      // 动态参数选中attr_Vals数组
      // manyAttrValsArr: [],
      // 当前商品三级分类 服务器获取固定属性 数据源
      // -----categoryAttrOnlyData: []----------------
    }
  },
  methods: {
    // Tab栏目切换标签之前的钩子,Tablan面板的切换激活联动步骤条
    handlePreventActiveChange (newActiveNum, oldActiveNum) {
      // 判断级联选择器是否选中三级分类 未选中阻止
      if (this.cascaderSelectTrueArr.length !== 3) {
        this.$notify({
          title: '分类未选择提示警告',
          message: '三级分类未选择,不允许切换新增商品面板！',
          type: 'warning',
          offset: 100
        })
        return false
      }
      // 判断表单信息是否填写完整,进行预校验,不完整不允许切换
      // this.$refs.addGoodBaseInfoFormRef.validate(valid => {
      //   if (!valid) {
      //     this.activeCurrentTab = newActiveNum - 0
      //     this.$message.info('商品基本信息存在不合法信息,请根据提示返回更正...')
      //     return false
      //   }
      // })
      //  --------------------------
    },
    // 处理Tabs标签页 变化
    handleTabsChange () {
      this.activeCurrentTab = this.selectCurrentTab - 0
      switch (this.selectCurrentTab) {
        case '1':
          this.getCategoryAttrParamsData(this.currentCategoryID, 'many')
          break
        case '2':
          this.getCategoryAttrParamsData(this.currentCategoryID, 'only')
      }
    },
    // 请求获取页面初始化加载商品分类信息
    async getCatgoryListData () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryOptionsData = res.data
    },
    // 级联选择器选中项数组变化
    handleSelectCategoryChange () {
      if (this.cascaderSelectTrueArr.length !== 3) {
        this.addGoodBaseInfoFormBool = true
        this.$refs.addGoodBaseInfoFormRef.resetFields()
        this.$notify({
          title: '商品分类提示警告',
          message: '新增商品必须选择所属三级分类!',
          type: 'warning',
          offset: 100
        })
        return
      }
      this.addGoodBaseInfoFormBool = false
      this.$refs.addGoodBaseInfoFormRef.resetFields()
      this.addGoodBaseInfoForm.goods_cat = this.cascaderSelectTrueArr.join(',')
      this.currentCategoryID = this.cascaderSelectTrueArr[this.cascaderSelectTrueArr.length - 1]
      // 获取到cascader的label值----------------------------------------------------------------------------------
      const cateNameArr = this.$refs.cascaderRef.getCheckedNodes()[0].pathLabels
      this.currentCategoryName = `当前三级分类为${cateNameArr[0]}，所属二级分类${cateNameArr[1]}的${cateNameArr[2]}`
    },
    // [封装]获取分类参数 动态/静态
    async getCategoryAttrParamsData (categoryID, attrSelType) {
      const { data: res } = await this.$http.get(`categories/${categoryID}/attributes`, { params: { sel: attrSelType } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.filter(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(', ') : []
        item.attrNew_vals = []
      })
      attrSelType === 'only' ? this.localCategoryAttrOnlyData = _.cloneDeep(res.data) : this.localCategoryAttrManyData = _.cloneDeep(res.data)
    },
    // 图上上传成功时的钩子函数
    handleUpSuccess (res) {
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      const upPicList = { pic: res.data.tmp_path }
      const showPicList = res.data
      this.srcList.push(showPicList.url)
      this.goodPicUploadFileList.push(showPicList)
      this.addGoodBaseInfoForm.pics.push(upPicList)
    },
    // 删除上传图片时的钩子函数
    async handleRemovePic (file) {
      const confirmRes = await this.$confirm('确定要移除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info('移除图片的操作被终止！')
      const showIndex = this.goodPicUploadFileList.findIndex(item => {
        return item.uid === file.file.uid
      })
      this.goodPicUploadFileList.splice(showIndex, 1)
      const upIndex = this.addGoodBaseInfoForm.pics.findIndex(item => {
        return item.tmp_path === file.file.tmp_path
      })
      this.addGoodBaseInfoForm.pics.splice(upIndex, 1)
      this.$message.success('图片已成功被移除！')
    },
    // 预览图片函数
    handlePictureCardPreview (file) {
      this.showPictureURL = file.file.url
      this.dialogShowPictureBool = true
    },
    // 信息完成预览所有提交信息
    handleTotlePanePage () {
      this.selectCurrentTab = '5'
      this.activeCurrentTab = this.selectCurrentTab - 0
    },
    // 确认提交新增商品信息
    handleAddGoodSubmit () {
      this.$refs.addGoodBaseInfoFormRef.validate(async valid => {
        if (!valid) return this.$message.warning('您的信息存在不合法信息，请检查填写必填项再进行重试！')
        // 处理动态参数
        this.localCategoryAttrManyData.forEach(item => {
          const attrManyNewStr = item.attrNew_vals.length !== 0 ? item.attrNew_vals.join(',') : ''
          const upAttrMany = { attr_id: item.attr_id, attr_value: attrManyNewStr }
          this.addGoodBaseInfoForm.attrs.push(upAttrMany)
        })
        // 处理固定属性
        this.localCategoryAttrOnlyData.forEach(item => {
          const attrOnlyNewStr = item.attrNew_vals.length !== 0 ? item.attrNew_vals.join(',') : ''
          const upAttrOnly = { attr_id: item.attr_id, attr_value: attrOnlyNewStr }
          this.addGoodBaseInfoForm.attrs.push(upAttrOnly)
        })
        // 发送请求新增商品
        const { data: res } = await this.$http.post('goods', this.addGoodBaseInfoForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 图片上传设置请求头携带token值
    setHeader () {
      return { Authorization: sessionStorage.getItem('token') }
    }
  }
}
</script>

<style lang="less" scoped>
/* 面包屑区域 */
.el-breadcrumb {
  margin-bottom: 12px;
}
/* 去除消息提示的p标签的内外间距 */
/deep/ .el-alert{
  p {
  padding: 0;
  margin: 0;
  p:first-child {
    margin-top: 5px;
  }
}
}
/* 商品完成步骤条 */
.el-steps {
  margin: 30px 0 10px 0;
  width: 100%;
}

/* 标签高度 */
/deep/ .el-tabs {
  height: 100%!important;
  .el-tabs__nav {
    .el-tabs__item {
      font-weight: 800;
    }
  }
}
/* 图片上传位置调整*/
.upload-pic {
  margin-top: 25px!important;
}

/* 去掉表单数字类型上下箭头 */
/deep/ input[type=number] {
    -moz-appearance:textfield;
}
/deep/ input[type=number]::-webkit-inner-spin-button,
/deep/ input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
/* 调整级联选择器标题的大小 */
/deep/ .el-tag--plain.el-tag--success {
  height: 40px;
  margin-right: 10px;
  line-height: 40px;
  font-size: 12px;
  font-weight: 800;
  vertical-align: middle;
}
/deep/ .el-cascader .el-input__inner {
  width: 340px;
}

// 图片上传展示
/deep/ .el-image {
  margin: 0 auto;
  width: 100%;
  height: 100%;
}
// 富文本编辑器调整
.quill-editor {
  margin: 20px 0 30px 0;
  /deep/.ql-editor {
    height: 300px;
  }
  /*滚动条整体样式*/
  /deep/ .ql-container ::-webkit-scrollbar{
    width: 10px;/*竖向滚动条的宽度*/
    height: 10px;/*横向滚动条的高度*/
  }
  /deep/ .ql-container ::-webkit-scrollbar-thumb{/*滚动条里面的小方块*/
    background: #666666;
    border-radius: 5px;
  }
  /deep/ .ql-container ::-webkit-scrollbar-track{/*滚动条轨道的样式*/
    background: #ccc;
  }
}
.goodAllReady {
  cursor: pointer;
}
.el-form-item {
  border-bottom: 1px solid gainsboro;
  /deep/ .el-form-item__label {
    font-weight: 600;
  }
  .el-tag {
    font-weight: 800;
  }
}

.submitBtn {
  height: 50px;
  line-height: 50px;
  font-weight: 700;
  font-size: 14px;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

</style>
